﻿var zombies = zombies || {};

zombies.ListCategory = function () {
    var self = this;
    self.Categories = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.SendMsg = function () {
        self.CurrentPage(1);
        load(self.CurrentPage(), self.SearchString());
        $.replaceUrl(self.CurrentPage(), self.SearchString());
    };

    self.EnterSendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }
    }

    self.CatId = ko.observable();
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.IconPath = ko.observable();

    self.CategoryData = ko.observable({
        CatId: self.CatId,
        Name: self.Name,
        Description: self.Description,
        IconPath: self.IconPath
    });

    self.itemTodel = ko.observable();

    self.getEditItem = function (item) {
        self.CatId(item.CatId);
        self.Name(item.Name);
        self.Description(item.Description);
        self.IconPath(item.IconPath);
    }
    self.doEdit = function () {
        var category = ko.utils.arrayFirst(self.Categories(), function (item) {
            return item.CatId === self.CatId();
        });
        $.ajax({
            type: "PUT",
            url: "/api/AdminCategory/PutCategory",
            data: ko.toJSON(self.CategoryData), //Convert the Observable Data into JSON
            contentType: "application/json",
            dataType: 'json'
        }).done(function () {
            toastr.success('Sửa Thành Công !');
            self.Categories.replace(category, {
                CatId: self.CatId(),
                Name: self.Name(),
                Description: self.Description(),
                IconPath: self.IconPath()
            });
            $('#editcat-div').removeClass('active in');
            $('#listcat-div').addClass('active in');
        }).fail(function () {
            toastr.error('Sửa Thất Bại !');
        });

    }

    self.doDelete = function (item) {
        $.confirm({
            text: "Bạn có chắc chắn xóa category tên: " + item.Name + " ?",
            title: "Xác Nhận Xóa",
            confirm: function (button) {
                $.ajax({
                    type: "DELETE",
                    url: "/api/AdminCategory/DeleteCategory/" + item.CatId,
                    success: function (data) {
                        self.Categories.remove(item);
                        toastr.success("Xóa Thành Công");
                        if (self.CurrentPage() > 1 && self.Advertises().length == 0) {
                            self.doPrevious();
                        } else {
                            load(self.CurrentPage(), self.SearchString);
                        }
                    },
                    error: function (error) {
                        toastr.error("Xóa thất bại");
                    }
                });
            },
            confirmButton: "Tiếp Tục Xóa",
            cancelButton: "Quay Lại"
        });
    }

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#cat-list'), -100);
        }
    }

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#cat-list'), -100);
        }
    }
}

var load = function (id, searchString) {
    viewModel.Loaded(true);
    viewModel.Categories.removeAll();
    $.ajax({
        url: '/api/AdminCategory/GetCategories/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 13) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.Categories.push(new zombies.Category(item));
        });
        viewModel.Loaded(false);
    }).error(function () {
        toastr.error('error');
    })
};

ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length)
                    var pre = $('#prethum');
                $.loadPreviewImg(element, pre);
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    var time = new Date($.now());
                    var fname = time.getTime() + $(element).prop("files")[0].name;
                    viewModel.IconPath("../Advertise/CategoryIcon/" + fname);
                    // this uses jquery.form.js plugin
                    $(element.form).ajaxSubmit({
                        url: url,
                        type: "POST",
                        dataType: "json",
                        data: { fname: fname },
                        headers: { "Content-Disposition": "attachment; filename=" + filename },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            // set viewModel property to IconPath
                            //bindingContext.$data[property](data);
                            viewModel.doEdit();
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
                else {
                    viewModel.doEdit();
                }
                return false;
            });
        }
    }
}


var pageUrl = $.getUrlVars("page");
var searchStringUrl = $.getUrlVars("searchString");
var viewModel;
$(document).ready(function () {

    viewModel = new zombies.ListCategory();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    load(viewModel.CurrentPage(), viewModel.SearchString());
});